package com.wangsd.web.face.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.extBean.PaymentReceiverRequest;
import com.wangsd.common.component.extBean.PaymentReceiverResponse;
import com.wangsd.common.component.WeixinPayService;
import com.wangsd.common.component.WxPayServiceExt;
import com.wangsd.web.face.entity.*;
import com.wangsd.web.face.mapper.MerchantMapper;
import com.wangsd.web.face.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-09-10
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Resource
    MerchantMapper merchantMapper;

    @Autowired
    AgentService agentService;
    @Autowired
    MerchantReceiverService merchantReceiverService;
    @Autowired
    ReceiverService receiverService;
    @Autowired
    ServiceBusinessService serviceBusinessService;
    @Autowired
    WeixinPayService weixinPayService;

    @Override
    public IPage<Merchant> selectList(Integer pageNum, Integer pageSize, Merchant params, String code) {
        Page<Merchant> page = new Page<>(pageNum, pageSize);
        IPage<Merchant> resultIPage = merchantMapper.selectListXml(page, params, code);
        return resultIPage;
    }

    @Override
    @Transactional
    public void addOrUpdate(Merchant params) {
        if (params.getId() != null) {
            merchantMapper.updateById(params);
        } else {
            merchantMapper.insert(params);

            //保留检索CODE
            Agent agent = agentService.getById(params.getAgentId());
            params.setCode(agent.getCode() + "-" + params.getId());
            merchantMapper.updateById(params);
        }
    }

    @Override
    public List<Map> selectAllByUserCode(String code) {
        List<Map> resultList = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.likeRight("code", code);
        }
        List<Merchant> list = merchantMapper.selectList(queryWrapper);
        for (Merchant merchant : list) {
            Map map = new HashMap();
            map.put("code", merchant.getCode());
            map.put("id", merchant.getId());
            map.put("name", merchant.getName());
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<Merchant> selectAllByCode(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.likeRight("code", code);
        }
        queryWrapper.eq("deleted", "0");
        List<Merchant> list = merchantMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public List<Merchant> selectByCode(String code) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.eq("code", code);
        }
        queryWrapper.eq("deleted", "0");
        List<Merchant> list = merchantMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public void addReceiver(Long merchantId, Long receiverId, Long drawTotalFee, Long minimumDraw, Long perDraw) throws Exception {
        try {
            //分账账户
            Receiver receiver = receiverService.getById(receiverId);
            //商户信息
            Merchant merchant = merchantMapper.selectById(merchantId);
            merchant.setPerDraw(perDraw);
            merchant.setDrawTotalFee(drawTotalFee);
            merchant.setMinimumDraw(minimumDraw);
            merchantMapper.updateById(merchant);

            if(receiverId != null){
                WxPayServiceExt wxPayServiceExt = weixinPayService.getServiceExt(merchant.getCode(), merchant.getSubMchId());
                //微信添加商户交易分账方
                PaymentReceiverRequest request = new PaymentReceiverRequest();
                request.setReceiver(JSON.toJSONString(receiver));
                request.setSignType(WxPayConstants.SignType.HMAC_SHA256);
                PaymentReceiverResponse receiverResponse = wxPayServiceExt.addreceiver(request);
                //HTTP状态和业务状态都为SUCCESS
                if (receiverResponse.getResultCode().equals(WxPayConstants.ResultCode.SUCCESS)
                        && receiverResponse.getReturnCode().equals(WxPayConstants.ResultCode.SUCCESS)) {
                    //本地保存分账方
                    MerchantReceiver merchantReceiver = new MerchantReceiver();
                    merchantReceiver.setMerchantId(merchantId);
                    merchantReceiver.setReceiverId(receiverId);
                    merchantReceiverService.save(merchantReceiver);
                }else{
                    throw new Exception("添加分账方失败");
                }
            }
        } catch (WxPayException e) {
            throw new Exception(e.getErrCodeDes());
        }
    }

    @Override
    public Result delMerchantReceiver(Long merchantId, Long receiverId) {
        //分账账户
        Receiver receiver = receiverService.getById(receiverId);
        //商户信息
        Merchant merchant = merchantMapper.selectById(merchantId);
        //获取服务商配置信息
        WxPayServiceExt wxPayServiceExt = weixinPayService.getServiceExt(merchant.getCode(), merchant.getSubMchId());

        try {
            //微信添加商户交易分账方
            PaymentReceiverRequest request = new PaymentReceiverRequest();
            request.setReceiver(JSON.toJSONString(receiver));
            request.setSignType(WxPayConstants.SignType.HMAC_SHA256);
            PaymentReceiverResponse receiverResponse = wxPayServiceExt.removereceiver(request);
            //HTTP状态和业务状态都为SUCCESS
            if (receiverResponse.getResultCode().equals(WxPayConstants.ResultCode.SUCCESS)
                    && WxPayConstants.ResultCode.SUCCESS.equals(receiverResponse.getReturnCode())) {
                //本地刪除分账方
                merchantReceiverService.delMerchantReceiver(merchantId, receiverId);
                return Result.success();
            } else {
                return Result.fail(receiverResponse.getReturnMsg());
            }
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return Result.fail("分账方刪除失败");
    }

    @Override
    public List<Receiver> selectMerchantReceivers(Long id) {
        List<Receiver> list = receiverService.selectByMerchantId(id);
        return list;
    }

    @Override
    public Merchant selectByDeviceNo(String deviceNo) {
        Merchant merchant = merchantMapper.selectByDeviceNoXml(deviceNo);
        return merchant;
    }

    @Override
    public Integer selectCountByAgentId(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("agent_id", id);
        queryWrapper.eq("deleted", "0");
        Integer count = merchantMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public Merchant selectByMiniAppId(String miniAppid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("mini_appid", miniAppid);
        Merchant merchant = merchantMapper.selectOne(queryWrapper);
        return merchant;
    }
}
